package cn.tedu.tmall.admin.mall.service.impl;

import cn.tedu.tmall.admin.mall.dao.cache.IOrderCacheRepository;
import cn.tedu.tmall.admin.mall.dao.persist.repository.IOrderRepository;
import cn.tedu.tmall.admin.mall.pojo.vo.OrderListItemVO;
import cn.tedu.tmall.admin.mall.pojo.vo.OrderStandardVO;
import cn.tedu.tmall.admin.mall.service.IOrderService;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.vo.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理订单数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Value("${tmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Value("${tmall.order.pay-overtime-in-minute}")
    private int payOvertimeInMinute;
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private IOrderCacheRepository orderCacheRepository;

    public OrderServiceImpl() {
        log.debug("创建业务类对象：OrderServiceImpl");
    }

    @Override
    public OrderStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询订单详情】的业务，参数：{}", id);
        OrderStandardVO queryResult = orderRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "查询订单失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<OrderListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询订单列表】的业务，页码：{}", pageNum);
        return orderRepository.list(pageNum, defaultQueryPageSize);
    }

    @Override
    public PageData<OrderListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询订单列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        return orderRepository.list(pageNum, pageSize);
    }

    @Override
    public int closeUnpaid() {
        log.debug("开始处理【关闭所有超时未支付订单】的业务，无参数");
        Long maxId = orderCacheRepository.getMaxId();
        int rows = 0;
        List<Long> idList = orderRepository.listOvertimeUnpaidIdList(payOvertimeInMinute, maxId);
        if (!idList.isEmpty()) {
            rows = orderRepository.updateStateByBatchIds(idList, ORDER_STATE_CLOSED_BY_SYSTEM);
            orderCacheRepository.setMaxId(idList.get(idList.size() - 1));
        }
        log.debug("成功关闭【{}】条超时未支付的订单", rows);
        return rows;
    }

}
